﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebClient.ShoppingCartModule;
using WebClient.ViewModels;
using WebClient.Helpers;
using WebClient.CF_DAL_WS;

namespace WebClient.Controllers
{
    [HandleError]
    public class HomeController : BaseController
    {
        /// <summary>
        /// Default index
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        /// <summary>
        /// Select district by idcity
        /// </summary>
        /// <param name="idcity"></param>
        /// <returns></returns>
        public ActionResult SelectDistricts(int idcity)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX,
                IDCity = idcity
            };
            return View("Index", CreateViewModel(data));
        }

        /// <summary>
        /// Select district by idcity
        /// </summary>
        /// <param name="idcity"></param>
        /// <returns></returns>
        [ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Restaurant_SearchCity(FormCollection forms)
		{
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_RESTAURANT,
                IDCity = int.Parse(forms.GetValues("ListCityHeader")[0])
            };
            ViewData["idcity"] = data.IDCity;
            return PartialView("Templates/TH_Search", CreateViewModel(data));
        }

        /// <summary>
        /// Select restaurant base on iddistrict and idfoodtype
        /// </summary>
        /// <param name="iddistrict"></param>
        /// <param name="idfoodtype"></param>
        /// <returns></returns>
        public ActionResult SelectRestaurants(int iddistrict, int idfoodtype)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_RESTAURANT,
                IDDistrict = iddistrict,
                IDFoodType = idfoodtype
            };
            return View("Restaurants", CreateViewModel(data));
        }

        public ActionResult Order(int idrestaurant)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER,
                IDRestaurant = idrestaurant
            };
            var groupViewModel = CreateViewModel(data);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            // Set up shoppingCart ViewModel
            groupViewModel.ShoppingCartModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };
            return View("Order", groupViewModel);
        }

        public ActionResult Cuisines(int idfoodtype)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CUISINES
            };
            ViewData["idfoodtype"] = idfoodtype;
            return View("Cuisines", CreateViewModel(data));
        }

        public ActionResult Cuisines_SelectDistricts(int idfoodtype, int idcity)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CUISINES,
                IDCity = idcity
            };
            ViewData["idfoodtype"] = idfoodtype;
            ViewData["idcity"] = idcity;
            return View("Cuisines", CreateViewModel(data));
        }

        public ActionResult SearchRestaurants(int idcity, int iddistrict, int idfoodtype)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_RESTAURANT,
                IDCity = idcity,
                IDDistrict = iddistrict,
                IDFoodType = idfoodtype
            };
            ViewData["idcity"] = idcity;
            ViewData["iddistrict"] = iddistrict;
            ViewData["idfoodtype"] = idfoodtype;

            return View("Restaurants", CreateViewModel(data));
        }

        ////////////////////// SHOPPING CART ////////////////////////
        public ActionResult AddToCart(int idrestaurant, int id, int num = 0)
        {
            // Retrieve the food from the database 
            var addedFood = _repFood.SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (cart.GetCartItems() != null && cart.GetCartItems().Count > 0)
            {
                if (idrestaurant != cart.GetCartItems()[0].RestaurantID)
                {
                    cart.EmptyCart();
                }
            }
            if (num == 0)
            {
                cart.AddToCart(idrestaurant, addedFood);
            }
            else
            {
                cart.AddToCart(idrestaurant, addedFood, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("Order", new { idrestaurant = idrestaurant });
        }

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the food to display confirmation 
            string foodName = _repFood.SelectByID(_repCart.SelectByRecordID(id.ToString()).FoodID).Name;

            // Remove from cart 
            cart.RemoveFromCart(id);

            // Display the confirmation message 
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(foodName) +
                    " has been removed from your shopping cart.",
                CartTotal = cart.GetTotal(),
                ItemCount = 0,
                DeleteId = id
            };

            return Json(results);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Approve(FormCollection forms)
        {
            string idrestaurant = forms.GetValues("txtRestaurant")[0];
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER,
                IDRestaurant = int.Parse(idrestaurant)
            };
            var groupViewModel = CreateViewModel(data);
            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            // Set up shoppingCart ViewModel
            groupViewModel.ShoppingCartModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };

            string username = string.Empty;
            // Redirect to 
            if (!AuthenticateSession(ref username))
            {
                ViewData["ViewApprove"] = "RequestLogin";
                return View("RequestLogin", groupViewModel);
            }
            groupViewModel.UsersModel = RetrieveUsersByUserNameViewModel(username);

            // User loggedin
            ViewData["ViewApprove"] = "ApproveOrder";
            return View("ApproveOrder", groupViewModel);
        }

        public ActionResult Approve(int idrestaurant)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER,
                IDRestaurant = idrestaurant
            };
            var groupViewModel = CreateViewModel(data);
            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            // Set up shoppingCart ViewModel
            groupViewModel.ShoppingCartModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };

            // Redirect to 
            string username = string.Empty;
            if (!AuthenticateSession(ref username))
            {
                ViewData["ViewApprove"] = "RequestLogin";
                return View("RequestLogin", groupViewModel);
            }
            groupViewModel.UsersModel = RetrieveUsersByUserNameViewModel(username);

            ViewData["ViewApprove"] = "ApproveOrder";
            // User loggedin
            return View("ApproveOrder", groupViewModel);
        }

        public ActionResult Contact()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddContact(FormCollection forms)
        {
            string email = forms.GetValues("Contact_Email")[0];
            string name = forms.GetValues("Contact_Name")[0];
            string subject = forms.GetValues("Contact_Subject")[0];
            string detail = forms.GetValues("Contact_Detail")[0];

            var newItem = new ContactDTO
            {
                Email = email,
                Name = name,
                Subject = subject,
                Detail = detail
            };
            var result = DALService.Instance.Contact_Insert(newItem);
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            ViewData["ContactResult"] = result ? "Your letter was sent, after consideration we will reply for you!" : "Your letter is not sent, have a problem in sending progress";
            return View("Contact", CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddOrder(FormCollection forms)
        {
            string idrestaurant = forms.GetValues("Order_IDRestaurant")[0];
            string idusers = forms.GetValues("Order_IDUsers")[0];
            string deliveryNote = forms.GetValues("Order_DeliveryNote")[0];
            string receiverName = forms.GetValues("Order_ReceiverName")[0];
            string receiverPhone = forms.GetValues("Order_ReceiverPhone")[0];
            string receiverAddress = forms.GetValues("Order_ReceiverAddress")[0];

            // First insert new order
            var newOrder = new OrdersDTO
            {
                IDRestaurant = int.Parse(idrestaurant),
                IDUsers = idusers,
                OrderDate = string.Format("{0:MM/dd/yyyy HH:mm:ss}", DateTime.Now),
                IsVerified = false,
                IsShipped = false,
                DeliveryNote = deliveryNote,
                ReceiverAddress = receiverAddress,
                ReceiverName = receiverName,
                ReceiverPhone = receiverPhone
            };

            var idInsertedOrder = DALService.Instance.Orders_Insert(newOrder);

            if (idInsertedOrder != -1)
            {
                // Next insert order details
                var cart = ShoppingCart.GetCart(this.HttpContext);
                foreach (var item in cart.GetCartItems())
                {
                    var food = DALService.Instance.Food_SelectByID(item.FoodID.ToString());
                    var orderDetail = new OrderDetailDTO
                    {
                        IDOrder = idInsertedOrder,
                        IDFood = item.FoodID,
                        Quantity = item.Count,
                        Price = food.Price
                    };
                    var result = DALService.Instance.OrderDetail_Insert(orderDetail);
                }
                cart.EmptyCart();
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                IDUsers = Guid.Parse(idusers)
            };
            ViewData["OrderResult"] = "Order successfull! we will process it as soon as possible";
            return View("OrdersHistory", CreateViewModel(data));
        }

        public ActionResult OrdersHistory(Guid iduser)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                IDUsers = iduser
            };
            return View(CreateViewModel(data));
        }

        public ActionResult SelectOrderDetailByIDOrder(Guid iduser, int idorder)
        {
            var data = new DataTransferViewModel
            {
                IDUsers = iduser,
                IDOrder = idorder,
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY_ORDERDETAIL,
            };
            return View("OrdersHistory", CreateViewModel(data));
        }

        public ActionResult ShowFoodDetail(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAIOF_FOOD,
                IDFood = id,
            };
            return View(CreateViewModel(data));
        }
    }
}
